package edu.buaa.resourceManager.controller;

import com.google.common.hash.Hashing;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import edu.buaa.resourceManager.helper.Utils;
import edu.buaa.resourceManager.store.JsonStore;
import edu.buaa.resourceManager.store.StoreDB;
import edu.buaa.resourceManager.vo.EZProjectFile;
import org.slf4j.Logger;
import spark.Route;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Scanner;

import static edu.buaa.resourceManager.helper.Utils.uriDecode;

/**
 * Created by song on 17-6-22.
 */
public class ImportController
{
    private static Logger log = Utils.getDevLogger();

    public static Route Page = (request, response) -> {
        response.type("text/html");
        return new Scanner(ImportController.class.getResourceAsStream("/html/import.html"), "UTF-8").useDelimiter("\\A").next();
    };

    public static Route FileInfo = (request, response) -> {
        String path = uriDecode(request.params(":path"));
        log.debug("importFileInfo {}", path);
        File file = new File(path);
        JsonObject object = new JsonObject();
        object.add("path", new JsonPrimitive(file.getAbsolutePath()));
        object.add("size", new JsonPrimitive(file.length()));
        try {
            BasicFileAttributes attr = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
            object.add("createTime", new JsonPrimitive(attr.creationTime().toMillis()));
            object.add("lastModifiedTime", new JsonPrimitive(attr.lastAccessTime().toMillis()));
        } catch (IOException ignore) {
            object.add("lastModifiedTime", new JsonPrimitive(file.lastModified()));
        }
        if(file.getName().toUpperCase().endsWith(".EZP")){
            EZProjectFile project = EZProjectFile.getEZProjectFile(new File(path));
            object.add("ezpInfo", JsonStore.getInstance().json.toJsonTree(project));
        }
        return object.toString();
    };

    public static Route FileHash = (request, response) -> {
        String path = uriDecode(request.params(":path"));
        File file = new File(path);
        String sha512 = com.google.common.io.Files.hash(file, Hashing.sha512()).toString();
        JsonObject object = new JsonObject();
        object.add("exist", new JsonPrimitive(StoreDB.getInstance().hasEntity(sha512)));
        object.add("md5head", new JsonPrimitive(
                file.length()>=10*1024*1024? Utils.getFileHeadMd5(file):""));
        object.add("sha512", new JsonPrimitive(sha512));
        return object.toString();
    };

    public static Route UploadFile = (request, response) -> {
        request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement("/temp"));
        Part field = request.raw().getPart("fileToUpload");
        String header = field.getHeader("Content-Disposition");
        String fileName = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
        log.debug("uploadFile {}", fileName);
        try (InputStream is = field.getInputStream()) {
            Files.copy(is, new File(fileName).toPath(), StandardCopyOption.REPLACE_EXISTING);
        }
        response.type("text/plain");
        return "File uploaded";
    };

}
